<template>
	<div style="display: flex; width: 100%; height: 30px">
		<el-select style="width: 140px; margin-right: 10px" size="default" v-model="province" placeholder="选择省" clearable>
			<el-option v-for="item in provincelist" :key="item.value.id" :label="item.label" :value="item.value" :disabled="item.disabled" />
		</el-select>
		<el-select style="width: 140px; margin-right: 10px" size="default" v-model="city" placeholder="选择市" clearable>
			<el-option v-for="item in optionsCity" :key="item.value.id" :label="item.label" :value="item.value" :disabled="item.disabled" />
		</el-select>
		<el-select style="width: 180px; margin-right: 10px" size="default" v-model="area" placeholder="选择区县" clearable>
			<el-option v-for="item in optionsArea" :key="item.value.id" :label="item.label" :value="item.value" :disabled="item.disabled" />
		</el-select>
	</div>
</template>
<script setup>
import { onMounted, toRefs, watch } from 'vue'
import { provinceList, cityList, areaList } from '@/api/custom/area'
const provincelist = ref([])
provinceList().then((res) => {
	provincelist.value = res.map((province) => ({
		label: province.shengName,
		value: province.shengId
	}))
})
const citylist = ref([])
cityList().then((res) => {
	for (let item of res) {
		const obj = { label: item.shiName, value: item.shiId }
		if (citylist[item.shengId ]) {
			citylist[item.shengId ].push(obj)
		} else {
			citylist[item.shengId ] = [obj]
		}
	}
	watch(province, () => {
		if (province.value) {
			optionsCity.value = citylist[province.value]
		} else {
			optionsCity.value = []
		}
		emit('update:provinceId', province.value)
	})
})
const arealist = ref([])
areaList().then((res) => {
	for (let item of res) {
		const obj = { label: item.quxianName, value: item.quxianId }
		if (arealist[item.shiId]) {
			arealist[item.shiId].push(obj)
		} else {
			arealist[item.shiId] = [obj]
		}
	}
	watch(city, () => {
		if (province.value && city.value) {
			optionsArea.value = arealist[city.value]
		} else {
			optionsArea.value = []
		}
		emit('update:cityId', city.value)
	})
})
const prop = defineProps({
	provinceId: Number,
	cityId: Number,
	areaId: Number
})

const emit = defineEmits(['update:provinceId', 'update:cityId', 'update:areaId'])

const province = ref('')
const city = ref('')
const area = ref('')
watch(prop, () => {
	setTimeout(() => {
		province.value = prop.provinceId
		city.value = prop.cityId
		area.value = prop.areaId
	}, 100)
})
const optionsCity = ref([])
const optionsArea = ref([])

watch(area, () => {
	emit('update:areaId', area.value)
})

const reset = () => {
	province.value = {}
}
defineExpose([reset])
</script>
